<?php
/**
 * Created by PhpStorm.
 * User: Sunqj
 * Date: 2017/2/16
 * Time: 上午8:36
 */
namespace app\bussiness\controller;

use app\common\model\Order;
use app\common\model\Pushlog;
use think\Controller;
use think\Exception;
use think\Log;
use think\Db;
use think\Loader;
use app\common\model\WeixinPay;

class PayNotify extends Controller
{

    public function weixin()
    {
        Log::log(file_get_contents("php://input"));
        $xml = file_get_contents('php://input');//获取微信返回来的通知

        //file_put_contents('./1.txt', $xml,FILE_APPEND);
        $arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);//解析数据

        if($arr=='')
        {
            $return = ['return_code'=>'FAIL','return_msg'=>'失败'];
        }else{

            if($arr['result_code']=="SUCCESS")
            {
                /*去掉其中的sign*/
                $old_sign=$arr['sign'];
                foreach ($arr as $k=>$v)
                {
                    if($k=='sign')
                    {
                        unset($arr[$k]);
                    }
                }

                $weixin=new WeixinPay();
                $sign=$weixin->getSign($arr);//根据返回的数据签名，和返回的签名比较是否一样

                //验签名。默认支持MD5
                if ( $sign === $old_sign) {;
                    //file_put_contents('./1.txt', 'ceshi',FILE_APPEND);
                    //   校验返回的订单金额是否与商户侧的订单金额一致。修改订单表中的支付状态。
                    $order_info = db('order')
                        ->where('ordersn', $arr['out_trade_no'])
                        ->find();
                    if($order_info&&$order_info['status']==0){
                        //有此订单且未支付
                        $real_price = $order_info['price']-$order_info['cash_coupon'];
                        $real_price = $real_price*100;
                        $real_price = intval($real_price);
                        if ($real_price != $arr['total_fee']) {

                            $return = ['return_code' => 'FAIL', 'return_msg' => '订单金额不对！'];
                            exit;
                        }

                        //微信支付-改为已支付
                        db('order')
                            ->where('id', $order_info['id'])
                            ->update(array(
                                'pay_time'=>date('Y-m-d H:i:s'),
                                'status' => 1,
                                'pay_type'=>1
                            ));
                        //删除此人无用订单
                        $this->del_nopayorder($order_info);

                        /*
                        //日志
                        db('paylog')
                            ->where('id', $order_info['ordersn'])
                            ->update(array(
                                'status' => 1,
                                'pay_time' => date('Y-m-d H:i:s'),
                                'pay_type'=>'wxpay'
                            ));
                        */
                        if($order_info['order_type']==1){
                            //普通订单
                            //修改demand表支付状态，类型，修改tblist表的支付状态，类型
                            if($order_info['type']==1||$order_info['type']==2){
                                //支付定金或全款
                                //需求和投标需改为开始制作
                                Db::name('demand')
                                    ->where('id',$order_info['xqid'])
                                    ->update(['status'=>3]);
                                Db::name('tblist')
                                    ->where('id',$order_info['tbid'])
                                    ->update(['order_status'=>2]);
                                $demand = Db::name('demand')
                                    ->where('id',$order_info['xqid'])
                                    ->field('name')
                                    ->find();
                                $tb = Db::name('tblist')
                                    ->where('id',$order_info['tbid'])
                                    ->field('uid')
                                    ->find();
                                if($demand&&$tb){
                                    if($order_info['type']==1){
                                        $sss = '定金';
                                    }else{
                                        $sss = '全款';
                                    }
                                    $content = '需求【'.$demand['name'].'】，用户已付'.$sss.'请尽快开始制作';
                                    Pushlog::send('付款通知',$content,$tb['uid'],7,'');
                                }
                            }elseif($order_info['type']==3){
                                //支付尾款
                                //不需要操作
                                $demand = Db::name('demand')
                                    ->where('id',$order_info['xqid'])
                                    ->field('name')
                                    ->find();
                                $tb = Db::name('tblist')
                                    ->where('id',$order_info['tbid'])
                                    ->field('uid')
                                    ->find();
                                if($demand&&$tb){
                                    $content = '需求【'.$demand['name'].'】，用户已付尾款，请尽快发货';
                                    Pushlog::send('付款通知',$content,$tb['uid'],8,'');
                                }
                            }else{

                            }
                        }else if($order_info['order_type']==2){
                            //代理费订单
                            $data['is_tg']=1;//成为推广员
                            Db::name('user')->where('id',$order_info['uid'])->update($data);
                            //推广奖励
                            $u= Db::name('user')->where('id',$order_info['uid'])->find();
                            if($u['parent_id']){
                                //一级上级
                                $u1=Db::name('user')->where(['id'=>$u['parent_id']])->find();

                                if($u1){
                                    $rate = Db::name('rate')->where('id',1)->find();

                                    if($u1['is_tg']==1){
                                        //计算推广人数
                                        $num1=Db::name('order')->where(['status'=>1,'order_type'=>2,'agaentid'=>$u1['id']])->count();
                                        if($num1<=3){//前3人每次返100
                                            $this->tglog($u1['id'],$order_info['uid'],$rate['back_one']);
                                            $this->mlog($u1['id'],$rate['back_one'],'推广奖励',2);
                                            $this->addmoney($u1['id'],$rate['back_one']);
                                        }else{//大于3 每次返40
                                            $this->tglog($u1['id'],$order_info['uid'],$rate['back_two']);
                                            $this->mlog($u1['id'],$rate['back_two'],'推广奖励',2);
                                            $this->addmoney($u1['id'],$rate['back_two']);
                                        }
                                    }

                                    if($u1['parent_id']){//二级
                                        $u2=Db::name('user')->where('id',$u1['parent_id'])->find();
                                        if($u2['is_tg']==1){//是推广员
                                            //返20
                                            $this->tglog($u2['id'],$order_info['uid'],$rate['back_friend']);
                                            $this->mlog($u2['id'],$rate['back_friend'],'推广奖励',2);
                                            $this->addmoney($u2['id'],$rate['back_friend']);
                                        }
                                    }
                                }
                            }
                        }else{
                            //注册费订单
                            //注册费改为缴纳
                            Db::name('user')->where('id',$order_info['uid'])->update(['is_reg'=>1]);
                        }
                    }

                    $return = ['return_code' => 'SUCCESS', 'return_msg' => 'OK'];
                }else{

                    $return = ['return_code'=>'FAIL','return_msg'=>'失败'];
                }
            }else{
                $return = ['return_code'=>'FAIL','return_msg'=>'失败'];
            }
        }


        $xml = '<xml>';
        foreach($return as $k=>$v){
            $xml.='<'.$k.'><![CDATA['.$v.']]></'.$k.'>';
        }
        $xml.='</xml>';

        echo $xml;
    }
    public function del_nopayorder($order_info){
        if($order_info['order_type']==1){
            $delcon['xqid'] = $order_info['xqid'];
            $delcon['tbid'] = $order_info['tbid'];
        }
        $delcon['order_type'] = $order_info['order_type'];
        $delcon['status'] = 0;
        $delcon['uid'] = $order_info['uid'];
        Db::name('order')->where($delcon)->delete();
    }
    //推广奖励变化日志
    public function tglog($uid,$xjid,$fee){
        $data2=array(
            'uid'=>$uid,
            'xjid'=>$xjid,
            'addtime'=>date('Y-m-d H:i:s'),
            'fee'=>$fee
        );
        Db::name('tglog')->insert($data2);
    }
    //余额变化日志
    public function mlog($uid,$money,$con,$type){
        $data2=array(
            'uid'=>$uid,
            'money'=>$money,
            'con'=>$con,
            'addtime'=>date('Y-m-d H:i:s'),
            'type'=>$type
        );
        Db::name('mlog')->insert($data2);
    }
    public function addmoney($uid,$money){
        $user = Db::name('user')->where('id',$uid)->setInc('money',$money);

    }
    /*支付宝回调*/
    public function ali()
    {
        $config = config('alipay');
        Loader::import('pcalipay.pagepay.service.AlipayTradeService');

        $arr=$_POST;
        $alipaySevice = new \AlipayTradeService($config);
        $alipaySevice->writeLog(var_export($_POST,true));
        $result = $alipaySevice->check($arr);

        if($result) {
            //验证成功

            //商户订单号
            $out_trade_no = $_POST['out_trade_no'];

            //支付宝交易号
            $trade_no = $_POST['trade_no'];

            //交易状态
            $trade_status = $_POST['trade_status'];


            if($_POST['trade_status'] == 'TRADE_FINISHED') {
                //距支付成功大约3月，支付宝会返回此参数，代表交易结束不能退款
                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            }else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
                //逻辑处理


                $total_amount = $_POST['total_amount'];//实际交易金额元

                //   校验返回的订单金额是否与商户侧的订单金额一致。修改订单表中的支付状态。
                $order_info = db('order')
                    ->where('ordersn', $out_trade_no)
                    ->find();
                if($order_info&&$order_info['status']==0){
                    //有此订单且未支付
                    $real_price = $order_info['price']-$order_info['cash_coupon'];

                    if ($real_price != $total_amount) {

                        $return = ['return_code' => 'FAIL', 'return_msg' => '订单金额不对！'];
                        exit;
                    }

                    //支付宝支付-改为已支付
                    db('order')
                        ->where('id', $order_info['id'])
                        ->update(array(
                            'pay_time'=>date('Y-m-d H:i:s'),
                            'status' => 1,
                            'pay_type'=>2
                        ));

                    //删除此人无用订单
                    $this->del_nopayorder($order_info);
                    /*
                    //日志
                    db('paylog')
                        ->where('id', $order_info['ordersn'])
                        ->update(array(
                            'status' => 1,
                            'pay_time' => date('Y-m-d H:i:s'),
                            'pay_type'=>'wxpay'
                        ));
                    */
                    if($order_info['order_type']==1){
                        //普通订单
                        //修改demand表支付状态，类型，修改tblist表的支付状态，类型
                        if($order_info['type']==1||$order_info['type']==2){
                            //支付定金或全款
                            //需求和投标需改为开始制作
                            Db::name('demand')
                                ->where('id',$order_info['xqid'])
                                ->update(['status'=>3]);
                            Db::name('tblist')
                                ->where('id',$order_info['tbid'])
                                ->update(['order_status'=>2]);
                            $demand = Db::name('demand')
                                ->where('id',$order_info['xqid'])
                                ->field('name')
                                ->find();
                            $tb = Db::name('tblist')
                                ->where('id',$order_info['tbid'])
                                ->field('uid')
                                ->find();
                            if($demand&&$tb){
                                if($order_info['type']==1){
                                    $sss = '定金';
                                }else{
                                    $sss = '全款';
                                }
                                $content = '需求【'.$demand['name'].'】，用户已付'.$sss.'请尽快开始制作';
                                Pushlog::send('付款通知',$content,$tb['uid'],7,'');
                            }
                        }elseif($order_info['type']==3){
                            //支付尾款
                            //不需要操作
                            $demand = Db::name('demand')
                                ->where('id',$order_info['xqid'])
                                ->field('name')
                                ->find();
                            $tb = Db::name('tblist')
                                ->where('id',$order_info['tbid'])
                                ->field('uid')
                                ->find();
                            if($demand&&$tb){
                                $content = '需求【'.$demand['name'].'】，用户已付尾款，请尽快发货';
                                Pushlog::send('付款通知',$content,$tb['uid'],8,'');
                            }
                        }else{

                        }
                    }else if($order_info['order_type']==2){
                        //代理费订单
                        $data['is_tg']=1;//成为推广员
                        Db::name('user')->where('id',$order_info['uid'])->update($data);
                        //推广奖励
                        $u= Db::name('user')->where('id',$order_info['uid'])->find();
                        if($u['parent_id']){
                            //一级上级
                            $u1=Db::name('user')->where(['id'=>$u['parent_id']])->find();

                            if($u1){
                                $rate = Db::name('rate')->where('id',1)->find();

                                if($u1['is_tg']==1){
                                    //计算推广人数
                                    $num1=Db::name('order')->where(['status'=>1,'order_type'=>2,'agaentid'=>$u1['id']])->count();
                                    if($num1<=3){//前3人每次返100
                                        $this->tglog($u1['id'],$order_info['uid'],$rate['back_one']);
                                        $this->mlog($u1['id'],$rate['back_one'],'推广奖励',2);
                                        $this->addmoney($u1['id'],$rate['back_one']);
                                    }else{//大于3 每次返40
                                        $this->tglog($u1['id'],$order_info['uid'],$rate['back_two']);
                                        $this->mlog($u1['id'],$rate['back_two'],'推广奖励',2);
                                        $this->addmoney($u1['id'],$rate['back_two']);
                                    }
                                }

                                if($u1['parent_id']){//二级
                                    $u2=Db::name('user')->where('id',$u1['parent_id'])->find();
                                    if($u2['is_tg']==1){//是推广员
                                        //返20
                                        $this->tglog($u2['id'],$order_info['uid'],$rate['back_friend']);
                                        $this->mlog($u2['id'],$rate['back_friend'],'推广奖励',2);
                                        $this->addmoney($u2['id'],$rate['back_friend']);
                                    }
                                }
                            }
                        }
                    }else{
                        //注册费订单
                        //注册费改为缴纳
                        Db::name('user')->where('id',$order_info['uid'])->update(['is_reg'=>1]);
                    }
                }
            }

            echo "success";	//请不要修改或删除
        }else {
            //验证失败
            echo "fail";

        }
    }
}